package com.gj.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: xiaobin
 * @create: 2020-12-14 23:58
 */
public class DlhFrameEncoder extends ByteToMessageCodec<Byte> {


    /**
     * @param ctx
     * @param msg
     * @param out
     * @see MessageToByteEncoder#encode(ChannelHandlerContext, Object, ByteBuf)
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, Byte msg, ByteBuf out) throws Exception {

    }

    /**
     * @param ctx
     * @param in
     * @param out
     * @see ByteToMessageDecoder#decode(ChannelHandlerContext, ByteBuf, List)
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        List<Byte> list = new ArrayList<>();
        for (int i = 0; i < in.writerIndex(); i ++) {
//            list.add(in.getByte(i));
//            System.out.println(i);
//            System.out.println(intTohex(in.getByte(i)));
            byte aByte = in.getByte(i);
//            System.out.println(aByte);
            out.add(aByte);
        }
//
//        for (byte i : list) {
//            System.out.println(i);
////            System.out.println(Integer.);
//        }
    }

    /**
     * 字节转十六进制
     * @param b 需要进行转换的byte字节
     * @return  转换后的Hex字符串
     */
    public static String byteToHex(byte b){
        String hex = Integer.toHexString(b & 0xFF);
        if(hex.length() < 2){
            hex = "0" + hex;
        }
        return hex;
    }
}
